package webcrawler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public class IdCardVerify {


    private IdCardVerify() {
    }

    public static final int[] W = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    public static final String PATTERN = "[1-9][\\d]{16}[x|X|0-9]";
    public static final Map<Integer, String> VAR_MPA = new HashMap<>();

    static {
        VAR_MPA.put(0, "1");
        VAR_MPA.put(1, "0");
        VAR_MPA.put(2, "x");
        VAR_MPA.put(3, "9");
        VAR_MPA.put(4, "8");
        VAR_MPA.put(5, "7");
        VAR_MPA.put(6, "6");
        VAR_MPA.put(7, "5");
        VAR_MPA.put(8, "4");
        VAR_MPA.put(9, "3");
        VAR_MPA.put(10, "2");
    }

    public static final boolean isVerify(String idCard) {
        if (idCard != null && Pattern.matches(PATTERN, idCard)) {
            String numArea = idCard.substring(0, 17);
            String last = idCard.substring(17);
            int totalNum = 0;
            for (int i = 0; i < W.length; i++) {
                String num = String.valueOf(numArea.charAt(i));
                totalNum += Integer.parseInt(num) * W[i];
            }
            int preVer = totalNum % 11;
            return last.equalsIgnoreCase(VAR_MPA.get(preVer));
        }
        return false;
    }

    public static List<String> hashIdCard(String verify, int startYear, String province) {
        return hashIdCard(verify, startYear, province, null);
    }

    public static List<String> hashIdCard(String verify, int startYear, String province, String city) {
        return hashIdCard(verify, startYear, province, city, null);
    }

    public static List<String> hashIdCard(String verify, int startYear, String province, String city, String district) {
        List<String> hashIdCards = new ArrayList<>();
        List<String> areaCodes = ChinaIdCardAreaCode.getIdCardList(verify, startYear, province, city, district);

        for (int i = 0; i < areaCodes.size(); i++) {
            String idCard = areaCodes.get(i);
            if (isVerify(idCard)) {
                hashIdCards.add(idCard);
                System.out.println(idCard);
            }
        }

        return hashIdCards;
    }
}
